<?php namespace Phpcmf\Controllers\Member;

class Admin extends \Phpcmf\App
{

    public function index() {

        $xid = intval($_GET['xid']);
        $rt = \Phpcmf\Service::M('xcx', 'xcx')->get_xcx_data($xid);
        if (!$rt['code']) {
            $this->_msg(0, $rt['msg']);
        }
        $this->_go($rt['data']);
    }

    public function order() {

        $id = intval($_GET['id']);
        $data = \Phpcmf\Service::M()->table_site('cloud_buy')->get($id);
        if (!$data) {
            $this->_msg(0, '此订单不存在');
        } elseif ( $data['status'] <= 0) {
            $this->_msg(0, '此订单没有交易成功');
        } elseif ($data['uid'] != $this->uid) {
            $this->_msg(0, '此订单不允许你操作');
        }

        $xcx = \Phpcmf\Service::M()->table('xcx')->where('oid', $id)->getRow();
        if (!$xcx) {
            // 开通小程序
            $shop = \Phpcmf\Service::M()->table_site('cloud')->where('id', intval($data['cid']))->getRow();
            if (!$shop) {
                $this->_msg(0, '关联商品不存在');
            }
            $save = [
                'cid' => $data['cid'],
                'oid' => $data['id'],
                'uid' => $data['uid'],
                'username' => $this->member['username'],
                'name' => $shop['title'],
                'logo' => $shop['thumb'],
                'setting' => ''
            ];
            $rt = \Phpcmf\Service::M('xcx', 'xcx')->install($save, $shop, $data);
            if ($rt['code']) {
                $this->_json(1, '创建成功');
            } else {
                $this->_json(0, $rt['msg']);
            }

            $save['id'] = $rt['code'];

            $rt = \Phpcmf\Service::M('xcx', 'xcx')->install($rt['data']);
            if (!$rt['code']) {
                $this->_json(0, $rt['msg']);
            }

            $this->_go($save);
        } else {
            $this->_go($xcx);
        }
    }

    private function _go($data) {

        $xcx_dir = 'api/xcx/'.$data['cid'].'/';

        if (!is_dir(WEBPATH.$xcx_dir)) {
            $this->_msg(0, '小程序文件目录不存在');
        }

        $url = $xcx_dir.'index.php?c=home&m=index&xid='.$data['id'];
        dr_redirect($url);
    }

}
